<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="90%"
    draggable
    @close="closeDialog"
  >
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="物料编号">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请输入物料编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetForm()"><i-ep-refresh />重置</el-button>
          <!-- <el-button
            class="ml-3"
            @click="
              useDownload(
                '/wms/wmsinventorycollection/export',
                '导出表格名称',
                searchParam
              )
            "
          >
            <template #icon><i-ep-download /></template>导出</el-button
          > -->
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template> </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :cell-style="cellStyle"
      >
        <el-table-column
          label="物料编号"
          prop="materialCode"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="物料名称"
          prop="materialName"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="仓库名称"
          prop="warehouseName"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="仓位名称"
          prop="binName"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="库存数量"
          prop="availableQuantity"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="盘点数量"
          prop="inventoryQuantity"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          label="差异数量"
          prop="differenceQuantity"
          min-width="100"
          show-overflow-tooltip
        />
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <template #footer>
      <div class="dialog-footer">
        <!-- <el-button type="primary" :loading="loading" @click="confirmData"
          >确 定</el-button 
        >-->
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <wmsinventoryprogress-edit
    :visible="addDialog.visible"
    :title="addDialog.title"
    :data="addDialog.data"
    @reset-table="(id: string) => (getTableList())"
    :is-readonly="addDialog.readvisible"
    @change-visible="changeVisible"
  />
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "WMSINVENTORYCOLLECTIONNEW",
  inheritAttrs: false,
});

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

// 请求参数
const requestApi = "/wms/wmsinventorytaskmaterial/differenceComparePage";

// 是否需要分页
const pagination = true;

const initParam = {};
// const visibleDialog = ref(false);
// 初始化搜索参数数据
const searchParamInit = {
  stockBatch: "",
  supplyBatch: "",
  customerId: "",
  organizationId: "",
  plantId: "",
  storageLocationId: "",
  warehouseId: "",
  storageTypeId: "",
  storageSectionId: "",
  binId: "",
  binCode: "",
  storageCode: "",
  materialCode: "",
  taskId: "", // 从父组件传入的inventoryTaskId会映射到这里
};

const deleteParam = {
  api: "/wms/wmsinventorycollection/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// 自定义表格状态
const tableData = ref([]);
const pageable = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const searchParam = ref({ ...searchParamInit });
const ids = ref([]);
const loading = ref(false);

// 自定义数据获取方法
async function getTableList() {
  if (!searchParam.value.taskId) {
    return;
  }
  
  loading.value = true;
  try {
    // 构造后端期望的参数格式
    const requestData = {
      data: {
        taskId: searchParam.value.taskId,
        materialCode: searchParam.value.materialCode || ""
      },
      pageNum: pageable.value.pageNum,
      pageSize: pageable.value.pageSize
    };
    
    const { data } = await request({
      url: requestApi,
      method: "post",
      data: requestData,
    });
    
    console.log('API response:', data);
    
    // 处理后端返回的分页数据
    if (data && data.records) {
      tableData.value = data.records || [];
      pageable.value.total = data.total || 0;
    } else {
      // 兼容非分页格式的返回
      tableData.value = data || [];
      pageable.value.total = data?.length || 0;
    }
  } catch (error) {
    requestError(error);
  } finally {
    loading.value = false;
  }
}

// 搜索方法
function search() {
  pageable.value.pageNum = 1; // 搜索时重置到第一页
  getTableList();
}

// 重置方法
function reset() {
  pageable.value.pageNum = 1; // 重置时回到第一页
  searchParam.value = { ...searchParamInit };
  getTableList();
}

// 分页方法
function handleSizeChange(val: number) {
  pageable.value.pageNum = 1; // 改变每页条数时重置到第一页
  pageable.value.pageSize = val;
  getTableList();
}

function handleCurrentChange(val: number) {
  pageable.value.pageNum = val;
  getTableList();
}

// 选择变化方法
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 删除方法
function handleTableDelete() {
  // 删除逻辑
}

onMounted(() => {
  if (props.data.taskId) {
    searchParam.value.taskId = props.data.taskId;
    getTableList();
  }
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    console.log('props.visible changed:', newVal);
    visibleDialog.value = newVal;
    if (newVal && props.data.taskId) {
      // 弹窗显示时，如果有taskId就调用接口
      console.log('Setting taskId:', props.data.taskId);
      searchParam.value.taskId = props.data.taskId;
      getTableList();
    } else if (!newVal) {
      // 弹窗关闭时，清空数据
      console.log('Dialog closed, clearing data');
      tableData.value = [];
      pageable.value.total = 0;
      searchParam.value = { ...searchParamInit };
    }
  }
);

/** 重置表单 */
function resetForm() {
  searchParam.value.storageTypeCode = "";
  searchParam.value.storageSectionCode = "";
  searchParam.value.binCode = "";
  searchParam.value.materialCode = "";
  searchParam.value.storageUnitCode = "";
  searchParam.value.storageCode = "";
  // 重置后重新调用接口
  getTableList();
}

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  // 清空数据，不调用接口
  tableData.value = [];
  pageable.value.total = 0;
  searchParam.value = { ...searchParamInit };
}

const dataTableRef = ref();
function confirmData() {
  console.log(
    "dataTableRef.value",
    dataTableRef.value,
    dataTableRef.value.getSelectionRows()
  );
  const list = dataTableRef.value.getSelectionRows();
  emit("select-row", list);

  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

const emit = defineEmits(["reset-table", "change-visible", "select-row"]);
// 查询详情
async function getInfo(id: string, taskId: string) {
  const { data } = await request({
    url: `/wms/wmsinventorycollection/getInventoryProgressMaterialInfoById`,
    method: "post",
    data: {
      id: id,
      taskId: taskId,
    },
  });
  addDialog.data = data;
}

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
/** 打开盘点计划表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    getInfo(roleObj.id, roleObj.taskId);
  }
  addDialog.title = "修改盘点数量";
  addDialog.readvisible = false;
  addDialog.visible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

const cellStyle = (data) => {
  console.log(data.row.balanced);
  if (data.row.balanced === 0) {
    return {
      color: "#000",
      background: "#FBE2E2",
      fontWeight: 700,
    };
  } else {
    return {
      color: "#000",
      background: "#AFE564",
      fontWeight: 700,
    };
  }
};
</script>
